package com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyActivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.diudiutechnology.www.yadiudiu.util.http.HttpClient;
import com.diudiutechnology.www.yadiudiu.util.http.JsonTools;
import com.diudiutechnology.www.yadiudiu.util.utils.Constant;
import com.diudiutechnology.www.yadiudiu.util.utils.ImgUtils;
import com.diudiutechnology.www.yadiudiu.util.utils.MyProgressDialog;
import com.diudiutechnology.www.yadiudiu.util.utils.PermissionsChecker;
import com.diudiutechnology.www.yadiudiu.util.utils.PictureUtil;
import com.diudiutechnology.www.yadiudiu.util.utils.SelectPhotoPop;
import com.diudiutechnology.www.yadiudiu.util.utils.Sundry;
import com.diudiutechnology.www.yadiudiu.util.utils.ToastUtils;
import com.diudiutechnology.www.yadiudiu.util.utils.UserInfoUtils;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyActivity.LoginActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyActivity.ImageManagementActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.mine.MyActivity.SelectTheAddressActivity;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.ApplicationModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MerchantsTypeModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.model.MineFragmentModel;
import com.diudiutechnology.www.yadiudiu.yadiudiu.main.MyApplication;
import com.diudiutechnology.www.yadiudiu.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;

/**
 * Created by Administrator on 2017/8/24.
 * 店铺资料
 */

public class StoreTheDataActivity extends Activity implements View.OnClickListener,Callback.CommonCallback<String> {
    @Bind(R.id.retur)
    LinearLayout retur;
    @Bind(R.id.title_right)//编辑
      TextView title_right;

    @Bind(R.id.note_information)//注意文字
   TextView note_information;

    @Bind(R.id.shop_introduction_layout)//店铺简介
    LinearLayout shop_introduction_layout;

    @Bind(R.id.address_shown)//可被编辑下 显示 显示地址
    LinearLayout address_shown;

    @Bind(R.id.invite_image_layout)//可被编辑下 显示 邀请码
            LinearLayout invite_image_layout;

    @Bind(R.id.business_address_layout)//可被保存 显示 编辑地址
    LinearLayout business_address_layout;

    @Bind(R.id.business_license)//企业照片
            ImageView business_license;


    @Bind(R.id.id_card_is)//身份证正面
            ImageView id_card_is;

    @Bind(R.id.id_card_back)//身份证反面
            ImageView id_card_back;


    @Bind(R.id.merchant_name)//商户 名称
            EditText merchant_name;
    @Bind(R.id.legal_name)//法人
            EditText legal_name;
    @Bind(R.id.id_number)//身份证号
            EditText id_number;

    @Bind(R.id.mobilephone)//手机号
            EditText mobilephone;
    @Bind(R.id.mail_box)//邮箱
            EditText mail_box;

    @Bind(R.id.provincial_text)//地址
            TextView provincial_text;
    @Bind(R.id.provincial)//地址
            TextView provincial;
    @Bind(R.id.provincial_edit)//详细地址
            EditText provincial_edit;
    @Bind(R.id.shop_introduction_edit)//店铺简介
            EditText shop_introduction_edit;

    @Bind(R.id.shop_introduction_text)//店铺简介
            TextView shop_introduction_text;
    @Bind(R.id.invitecode)//自己的邀请码
            TextView invitecode;

    @Bind(R.id.image_management_layout)//图片管理
    RelativeLayout image_management_layout;
    int pos=0;//0、可被编辑  1、可被保存
    Context context;
    String Judge_interface="0";//判断哪个接口   0、获取店铺资料 1、上传图片 2、上传店铺资料
    private MyProgressDialog mDialog;
    List<ApplicationModel> list=new ArrayList<>();
    private DisplayImageOptions options;
    private ImageLoader imageLoader;
    String Judge_number="0";//判断哪个图片   0、身份证正面 1、身份证反面 3、营业执照
    String justimg="";//正面图片路径
    String backimg="";//反面图片路径
    String businessimg="";//营业执照
    private SelectPhotoPop selectPhotoPop;
    private  View  viewkre;
    String province ="";//省
    String city   ="";// 市
    String area ="";//  区
    String longitude ="";//   经度
    String latitude  ="";//  纬度
    String typeid="";
    String u_id="";
    String merchanttype="";//类型
    String invite="";//别人的邀请码
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        viewkre= View.inflate(this, R.layout.activity_store_the_data, null);
        setContentView(viewkre);
        ButterKnife.bind(this);
        context=this;
        initView();
    }

    private void initView() {
        retur.setOnClickListener(this);
        title_right.setOnClickListener(this);
        business_license.setOnClickListener(this);
        id_card_is.setOnClickListener(this);
        id_card_back.setOnClickListener(this);
        image_management_layout.setOnClickListener(this);
        options = ImgUtils.imageOptions();
        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(context));

        if(getIntent()!=null){
            u_id=getIntent().getStringExtra("id");
        }
        processnNotEdit();
        initData();
    }
    //绑定逻辑
    private void initData(){
        MineFragmentModel mineFragmentModel = UserInfoUtils.readUserInfo(this);
        merchanttype=mineFragmentModel.getMerchanttype();
        if (merchanttype.equals("1")){//房产商家
            //店铺简介隐藏
            shop_introduction_layout.setVisibility(View.GONE);
        }else if (merchanttype.equals("2")){//购车商家
            //店铺简介隐藏
            shop_introduction_layout.setVisibility(View.GONE);
        }else if (merchanttype.equals("3")){//干洗商家

        }else if (merchanttype.equals("4")){//开锁商家

        }else if (merchanttype.equals("5")){//果蔬商家

        }else if (merchanttype.equals("6")){//苦力商家

        }else if (merchanttype.equals("7")){//快递商家

        }else if (merchanttype.equals("8")){//家政商家

        }else if (merchanttype.equals("9")){//洗车商家
            //店铺简介隐藏
            shop_introduction_layout.setVisibility(View.GONE);
        }
        businesses ();
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retur:
                finish();
                break;
            case R.id.title_right:
                if(pos==0){
                    pos=1;
                    title_right.setText("保存");
                    address_shown.setVisibility(View.GONE);
                    business_address_layout.setVisibility(View.VISIBLE);
                    invite_image_layout.setVisibility(View.GONE);
                    note_information.setVisibility(View.VISIBLE);
                    processEdit();
                }else {
                    processSubmitdata();
                }
                break;
            case R.id.business_license://企业照片
                if(pos==1){//可点击
                    processadd("2");
                }
                break;
            case R.id.id_card_is://身份证正面
                if(pos==1){//可点击
                    processadd("0");
                }
                break;
            case R.id.id_card_back://身份证反面
                if(pos==1){//可点击
                    processadd("1");
                }
                break;
            case R.id.image_management_layout:
                Intent intents = new Intent(context, ImageManagementActivity.class);
                intents.putExtra("id",u_id);
                startActivity(intents);
                break;
                  		/* 注释  相机*/
            case R.id.item_popupwindows_camera:
                selectPhotoPop.dismiss();
                GalleryFinal.openCamera(Constant.CAMERA, MyApplication.getInstance().initGalley(Constant.CAMERA,1), mOnHanlderResultCallback);
                break;
            /* 注释  相册*/
            case R.id.item_popupwindows_Photo:
                selectPhotoPop.dismiss();
                GalleryFinal.openGallerySingle(Constant.GALLERYSINGLE, MyApplication.getInstance().initGalley(Constant.GALLERYSINGLE,1), mOnHanlderResultCallback);
                break;
            /* 注释  取消*/
            case R.id.item_popupwindows_cancel:
                selectPhotoPop.dismiss();
                break;
            case R.id.provincial_layou:
                Intent intent = new Intent(context, SelectTheAddressActivity.class);
                intent.putExtra("pos","2");
                startActivityForResult(intent, Constant.MODIFICATION);
                break;
        }
    }
    private void processSubmitdata(){

        if (TextUtils.isEmpty(merchant_name.getText().toString().trim())){//商户名称
            ToastUtils.show(context, getResources().getString(R.string.please_name));
            return;
        }
        if (TextUtils.isEmpty(legal_name.getText().toString().trim())){//法人姓名
            ToastUtils.show(context, getResources().getString(R.string.please_legal_name));
            return;
        }
        if (TextUtils.isEmpty(id_number.getText().toString().trim())){//身份证号
            ToastUtils.show(context, getResources().getString(R.string.please_id_number));
            return;
        }
        if (!Sundry.personIdValidation(id_number.getText().toString())){//正确的身份证号
            ToastUtils.show(this,getResources().getString(R.string.please_correct_id_number));
            return;
        }
        if (TextUtils.isEmpty(mobilephone.getText().toString().trim())){//手机号
            ToastUtils.show(context, getResources().getString(R.string.please_phone_number));
            return;
        }
        if (!Sundry.isMobileNO(mobilephone.getText().toString().trim())){//验证手机号
            ToastUtils.show(context, getResources().getString(R.string.please_correctness_phone_number));
            return;
        }
        if (TextUtils.isEmpty(mail_box.getText().toString().trim())){//邮箱
            ToastUtils.show(context, getResources().getString(R.string.please_box));
            return;
        }
        if (!Sundry.checkEmail(mail_box.getText().toString().trim())){//邮箱
            ToastUtils.show(context, getResources().getString(R.string.please_correctness));
            return;
        }
        if (TextUtils.isEmpty(justimg)){//身份证正面
            ToastUtils.show(context, getResources().getString(R.string.please_front));
            return;
        }
        if (TextUtils.isEmpty(backimg)){//身份证反面
            ToastUtils.show(context, getResources().getString(R.string.please_reverse));
            return;
        }
        if (TextUtils.isEmpty(businessimg)){//营业执照
            ToastUtils.show(context, getResources().getString(R.string.please_busines));
            return;
        }
        if (TextUtils.isEmpty(provincial.getText().toString().trim())){//省市区
            ToastUtils.show(context, getResources().getString(R.string.please_select_address));
            return;
        }
        if (TextUtils.isEmpty(provincial_edit.getText().toString().trim())){//详细地址
            ToastUtils.show(context, getResources().getString(R.string.specific_address));
            return;
        }
        processmodifieddata();
    }
    public void processEdit(){//保存
        merchant_name.setEnabled(true);
        legal_name.setEnabled(true);
        mobilephone.setEnabled(true);
        mail_box.setEnabled(true);
        id_number.setEnabled(true);
    }
    public void processnNotEdit(){//编辑
        merchant_name.setEnabled(false);
        legal_name.setEnabled(false);
        mobilephone.setEnabled(false);
        mail_box.setEnabled(false);
        id_number.setEnabled(false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("stringmd5="+requestCode+"resultCode="+resultCode);
        if (resultCode==Constant.MODIFICATION){
            if (requestCode==Constant.MODIFICATION){
                provincial_edit.setText(data.getStringExtra("address"));
                province =data.getStringExtra("province");//省
                city =data.getStringExtra("city");// 市
                area =data.getStringExtra("district");//  区
                longitude =data.getStringExtra("longitude");//   经度
                latitude  =data.getStringExtra("latitude");//  纬度
                provincial.setText(province+","+city+","+area);
            }
        }
    }
    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
            Bitmap bitmap = PictureUtil.decodeSampledBitmapFromFile(resultList.get(0).getPhotoPath(), Constant.WIDE, Constant.WIDE);
            String conimg  =PictureUtil.saveBitmapFile(bitmap, String.valueOf(0));
            processupload(conimg);
        }
        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {

        }
    };
    //调用相机
    private void processadd(String pos){
        if (!PermissionsChecker.getPermissionsChecker(this, "0", 0)) {
            if (!PermissionsChecker.getPermissionsChecker(this, "0", 2)) {
                Judge_number=pos;
                showSelectPicPop();
            } else {
                ToastUtils.show(context, "请检查是否打开储存权限");
            }
        } else {
            ToastUtils.show(context, "请检查是否打开相机权限");
        }
    }
    //相册
    private void showSelectPicPop() {
        selectPhotoPop = new SelectPhotoPop(this, this);
        selectPhotoPop.showAtLocation(viewkre, Gravity.BOTTOM, 0, 0);
    }
    //商家查看
    private void businesses (){
        if (Sundry.isOpenNetwork(context)){
            Judge_interface="0";
            mDialog =new MyProgressDialog(context);
            HttpClient.shopdetails(u_id,this);
        }else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }

    //上传图片
    private void processupload(String upload ){
        if (Sundry.isOpenNetwork(context)){
            Judge_interface="1";
            mDialog =new MyProgressDialog(context);
            HttpClient.upload(upload,this);
        }else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }
    //修改申请商家
    private void processmodifieddata(){
        if (Sundry.isOpenNetwork(context)){
            Judge_interface="2";
            mDialog =new MyProgressDialog(context);
            HttpClient.modifieddata(u_id,"",merchant_name.getText().toString().trim(),typeid,legal_name.getText().toString().trim(),mobilephone.getText().toString().trim(),
                    province,city,area,provincial_edit.getText().toString().trim(),longitude,latitude,mail_box.getText().toString().trim(),
                    businessimg,justimg,backimg,invite,id_number.getText().toString().trim(),shop_introduction_edit.getText().toString().trim(),this);

        }else {
            ToastUtils.Toastshow(context, getResources().getString(R.string.network));
        }
    }
    @Override
    public void onSuccess(String result) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        System.out.println("stringmd5result"+result);
        List<MerchantsTypeModel> getnote = JsonTools.getmerchanttype(result);
        if (getnote!=null||getnote.size()>0){
            String error = getnote.get(0).getError();
            String mssage = getnote.get(0).getMssage();
            if (error.equals("200")){

                String content = getnote.get(0).getResult();
                if (Judge_interface.equals("0")){//类型
                    list= JsonTools.getbusiness(content);

                    if (list!=null||list.size()>0){
                        processData();
                    }
                }else if (Judge_interface.equals("1")){//图片
                    if (Judge_number.equals("0")){//身份证正面
                        justimg=content;
                        imageLoader.displayImage(Constant.HTTP+content, id_card_is, options);
                    }else  if (Judge_number.equals("1")){//身份证反面
                        backimg=content;
                        imageLoader.displayImage(Constant.HTTP+content, id_card_back, options);
                    }else if (Judge_number.equals("2")){//营业执照
                        businessimg=content;
                        imageLoader.displayImage(Constant.HTTP+content, business_license, options);
                    }
                }else if (Judge_interface.equals("2")){// 申请
                    businesses ();
                    pos=0;
                    address_shown.setVisibility(View.VISIBLE);
                    business_address_layout.setVisibility(View.GONE);
                    title_right.setText("编辑");
                    invite_image_layout.setVisibility(View.VISIBLE);
                    note_information.setVisibility(View.GONE);
                    processnNotEdit();
                    ToastUtils.show(context, mssage);
                }
            }else if (error.equals("105")){
                Intent intent = new Intent(context, LoginActivity.class);
                startActivity(intent);
                ToastUtils.show(context, mssage);
            }else {
                ToastUtils.show(context, mssage);
            }
        }
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onCancelled(CancelledException cex) {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        ToastUtils.Toastshow(context, getResources().getString(R.string.server));
    }

    @Override
    public void onFinished() {

    }
    //绑定数据
    private void processData(){
        ApplicationModel applicationModel = list.get(0);
        provincial_edit.setText(applicationModel.getSuite());
        province =applicationModel.getProvince();//省
        city =applicationModel.getCity();// 市
        area =applicationModel.getDist();//  区
        longitude =applicationModel.getLongitude();//   经度
        latitude  =applicationModel.getLatitude();//  纬度
        provincial.setText(province+","+city+","+area);
        provincial_text.setText(province+city+area+applicationModel.getSuite());
        justimg=applicationModel.getIdcardfront();//正面图片路径
        imageLoader.displayImage(Constant.HTTP+justimg, id_card_is, options);
        backimg=applicationModel.getIdcardreverse();//反面图片路径
        imageLoader.displayImage(Constant.HTTP+backimg, id_card_back, options);
        businessimg=applicationModel.getLicense();//营业执照
        imageLoader.displayImage(Constant.HTTP+businessimg, business_license, options);
        merchant_name.setText(applicationModel.getName());// 商户名称
        legal_name.setText(applicationModel.getLegalname());//法人代表
        mobilephone.setText(applicationModel.getPhone());// 电话
        mail_box.setText(applicationModel.getEmail());//邮箱
        invite=applicationModel.getBeinvitedcode();//别人的邀请
        id_number.setText(applicationModel.getIdcardno());//身份证号
        typeid=applicationModel.getMerchanttype();
        shop_introduction_text.setText(applicationModel.getProfile());//店铺简介
        shop_introduction_edit.setText(applicationModel.getProfile());//店铺简介
        invitecode.setText(applicationModel.getInvitecode());//自己的邀请码
    }
}

